﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JX.Infrastructure.LoadBalancer
{
    /// <summary>
    /// 轮询算法 负载平衡器
    /// </summary>
    public class RoundRobinLoadBalancer : ILoadBalancer
    {
        private readonly object _lock = new object();
        private int _index = 0;

        /// <summary>
        /// 根据轮询算法，解析出需要的元素
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sequence"></param>
        /// <returns></returns>
        public T Resolve<T>(IEnumerable<T> sequence)
        {
            var items = sequence.ToList();
            // 使用lock控制并发
            lock (_lock)
            {
                if (_index >= items.Count)
                {
                    _index = 0;
                }
                return items[_index++];
            }
        }
    }
}
